﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WeManageService
{
    public class TurnoverManager
    {
        static public int nextID;
        static public List<Turnover> flow;
        static public bool inited = false;

        public static int GetNextID()
        {
            int oid = nextID++;
            FileManager.TurnoverNextID = nextID;
            FileManager.Write();
            return oid;
        }

        public static void Initialrize(string userName)
        {
            TurnoverDBManager dbManager = new TurnoverDBManager();
            //初次初始化时 读取nextID
            if (!inited)
            {
                FileManager.Read();
                nextID = FileManager.TurnoverNextID;
                inited = true;

                //如果遇到文件损坏的情况 则进行恢复处理
                //处理耗时可能较长 所以一般情况下仍从文件读取
                if (nextID == 1)
                {
                    List<Turnover> allTurnovers = dbManager.GetAllTurnover();
                    if (allTurnovers.Count != 0)
                        nextID = dbManager.GetAllTurnover().Max(p => p.TurnoverID) + 1;
                }
            }
            flow = dbManager.GetUserTurnover(userName);
        }

        public static void AddTurnover(Turnover t)
        {
            TurnoverDBManager dbManager = new TurnoverDBManager();
            t.TurnoverID = GetNextID();
            dbManager.AddTurnover(t);
            flow.Add(t);
        }
    }
}
